package com.aifingding.count;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 * 统计代码行数并导出带行号的汇总源文件
 * @author Eric Wu
 * @date 2022年11月22日
 */
public class BatchCountExportSourceCode {
   public static void main(String[] args) {
	//需要扫描的源文件根目录
	String sourceFolderPath = "E:/WORK/IDE/workspace_dev/traffic";
	//需要扫描的的文件类型，自己可以进行定义
	String [] fileFormat = new String[]{".java",".html",".vue",".css",".js"};
	//源文件会导出汇总到这一个文件里
	String targetFilePath = "D:/源代码汇总.txt";
	FileWriter fw = null;
	try {
		fw = new FileWriter(new File(targetFilePath));
		int totalLine = outputContentByFile(new File(sourceFolderPath), 1, fileFormat, fw);
		System.out.println(totalLine);
	} catch (IOException e) {
		e.printStackTrace();
	}finally {
		try {
			if(fw!=null){
				fw.close();
			}
		} catch (IOException e) {
			//ignore
		}
	}
}
   
    public static int outputContentByFile(File file,int startLine,String[] fileFormat,FileWriter targetWriter) throws IOException{
    	if(file.isDirectory()){
    		File[] listFiles = file.listFiles();
    		for(File childFile : listFiles){
    			startLine = outputContentByFile(childFile,startLine,fileFormat,targetWriter);
    		}
    	}else{
    		boolean isCanRead = false;
    		for(String format : fileFormat){
    			if(file.getName().endsWith(format)){
    				isCanRead = true;
    				break;
    			}
    		}
    		if(isCanRead){
    			CodeFile codeFile = readFileContent(file.getAbsolutePath(),startLine);
        		targetWriter.write(codeFile.getContent());
        		return codeFile.getEndLine();
    		}
    	}
    	return startLine;
    }
    

	/**
     * 读取文件内容
     * @param path 要读取的文件
     * @param startLine 起始行号
     * @return 文件内容
     */
	public static CodeFile readFileContent(String path,int startLine) {
		CodeFile codeFile = new CodeFile();
		codeFile.setStartLine(startLine);
		File file = new File(path);
		FileReader fr = null;
		BufferedReader bf = null;
		try {
			fr = new FileReader(file);
			bf = new BufferedReader(fr);
			String str = "";
			StringBuilder sb = new StringBuilder(str);
			int i = startLine;
			//按行读
			while ((str = bf.readLine()) != null) {
				// 忽略空行
				if (!str.trim().isEmpty()) {
					sb.append(i+"");
					sb.append(str);
					sb.append("\n");
					i++;
				}
			}
			codeFile.setEndLine(i);
			codeFile.setContent(sb.toString());
			return codeFile;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bf != null) {
					bf.close();
				}
			} catch (IOException e) {
				// ignore
			}
			try {
				if (fr != null) {
					fr.close();
				}
			} catch (IOException e) {
				// ignore
			}
		}
		return codeFile;
	}
}
